/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package by.scsbsu.commands;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import by.scsbsu.logic.LoginLogic;
import by.scsbsu.resources.managers.CookiesManager;
import by.scsbsu.resources.managers.MessageManager;
import by.scsbsu.resources.managers.PageLinksManager;

public class LoginCommand implements Command {

    private static final String PARAM_NAME_LOGIN = "user_name";
    private static final String PARAM_NAME_PASSWORD = "user_password";

    @Override
    public String execute(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException {

        String page = null;
        String login = request.getParameter(PARAM_NAME_LOGIN);
        String password = request.getParameter(PARAM_NAME_PASSWORD);
        if (LoginLogic.checkLogin(login, password)) {
        	response.addCookie(CookiesManager.createCookie(CookiesManager.C_K_USER, login));
        	response.addCookie(CookiesManager.createCookie(CookiesManager.C_K_PASS, password));
        	if(request.getParameter("remember_me") != null) {
        		response.addCookie(CookiesManager.createCookie(CookiesManager.C_K_SAVE, "true"));
        	} else {
        		response.addCookie(CookiesManager.createCookie(CookiesManager.C_K_SAVE, "false"));
        	}
            request.setAttribute("user", login);
            request.setAttribute("selectedScreen", PageLinksManager.getProperty(PageLinksManager.MAIN_PAGE_PATH));
            page = PageLinksManager.getProperty(PageLinksManager.TEMPLATE_PAGE_PATH);
        } else {
            request.setAttribute("error_login", MessageManager.getProperty(MessageManager.LOGIN_ERROR_MESSAGE));
            page = PageLinksManager.getProperty(PageLinksManager.LOGIN_PAGE_PATH);
        }
        return page;
    }
}
